package com.wkbb.common.utils.excelUtil;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.wkbb.common.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * String to date converter
 *
 * @author wuxq
 */
@Slf4j

public class CustomStringDateConverter implements Converter<Date> {

    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里读的时候会调用
     *
     * @param cellData
     *            NotNull
     * @param contentProperty
     *            Nullable
     * @param globalConfiguration
     *            NotNull
     * @return
     */
    @Override
    public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
                                  GlobalConfiguration globalConfiguration) {
        String value = null;
//        return "自定义：" + cellData.getStringValue();
        log.debug("解析到一列数据,数据类型:{}", cellData.getType());

        value = cellData.getStringValue();

        log.info("解析到一列数据,转换后为:{}", value);

        if(null != value) {
            //对日期字符串进行统一格式化
            //兼容2019-10-20
            value = value.replace("/", "-");

            //兼容2019年10月20日
            value = value.replace("年", "-");
            value = value.replace("月", "-");
            value = value.replace("日", "-");
            value = value.replace("时", "-");
            value = value.replace("分", "-");
            value = value.replace("秒", "-");

            //兼容2019.10.20
            value = value.replace(".", "-");

            log.debug("时间格式经转换后:{}", value);

            try {
                return TimeUtil.toDateYYYY_MM_DD(value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 这里是写的时候会调用 不用管
     *
     * @param date
     *            NotNull
     * @param contentProperty
     *            Nullable
     * @param globalConfiguration
     *            NotNull
     * @return
     */
    @Override
    public CellData convertToExcelData(Date date, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) {
        return new CellData(TimeUtil.toStringYYYY_MM_DD(date));
    }

}
